package com.ruoyi.exam.controller;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;

import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.exam.domain.ExamAnalyze;
import com.ruoyi.exam.domain.ExamUserInfo;
import com.ruoyi.exam.domain.ExamUserOrder;
import com.ruoyi.exam.service.IExamAnalyzeService;
import com.ruoyi.exam.service.impl.ExamUserInfoServiceImpl;
import com.ruoyi.exam.service.impl.ExamUserOrderServiceImpl;
import com.ruoyi.exam.util.AiUtil;
import com.ruoyi.exam.websocket.AiWebSocket;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

/**
 * 分析情况Controller
 *
 * @author wky
 * @date 2024-09-19
 */
@RestController
@RequestMapping("/exam/analyze")
@Tag(name = "【分析情况】管理")
public class ExamAnalyzeController extends BaseController {
    @Autowired
    private IExamAnalyzeService examAnalyzeService;

    @Autowired
    private ExamUserOrderServiceImpl userOrderService;

    @Autowired
    private ExamUserInfoServiceImpl userInfoService;

    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");

    /**
     * 查询分析情况列表
     */
    @Operation(summary = "查询分析情况列表")
    @PreAuthorize("@ss.hasPermi('exam:analyze:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExamAnalyze examAnalyze) {
        startPage();
        List<ExamAnalyze> list = examAnalyzeService.selectExamAnalyzeList(examAnalyze);
        return getDataTable(list);
    }

    /**
     * 导出分析情况列表
     */
    @Operation(summary = "导出分析情况列表")
    @PreAuthorize("@ss.hasPermi('exam:analyze:export')")
    @Log(title = "分析情况", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExamAnalyze examAnalyze) {
        List<ExamAnalyze> list = examAnalyzeService.selectExamAnalyzeList(examAnalyze);
        ExcelUtil<ExamAnalyze> util = new ExcelUtil<ExamAnalyze>(ExamAnalyze.class);
        util.exportExcel(response, list, "分析情况数据");
    }

    /**
     * 获取分析情况详细信息
     */
    @Operation(summary = "获取分析情况详细信息")
    @PreAuthorize("@ss.hasPermi('exam:analyze:query')")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        return success(examAnalyzeService.selectExamAnalyzeByUserId(userId));
    }

    @GetMapping("/isAlowAnalyze")
    public AjaxResult isAvailableAnylaze() {
        ExamUserOrder temp = new ExamUserOrder();
        temp.setUserId(getUserId());
        temp.setOrderType(ExamUserOrder.SINGLE_ANALYZE);
        return success(Boolean.valueOf(userOrderService.selectExamUserOrderList(temp).size() > 0));
    }

    @GetMapping("/isAlowAi")
    public AjaxResult isAvailableAi() {
        ExamUserOrder examUserOrder = new ExamUserOrder();
        examUserOrder.setCreateBy(getUsername());
        examUserOrder.setOrderType(ExamUserOrder.AI_ANALYZE);
        examUserOrder.setUserId(getUserId());
        return success(Boolean.valueOf(userOrderService.selectExamUserOrderList(examUserOrder).size() > 0));
    }

    @GetMapping("/getAnalyze")
    public AjaxResult doAnalyze() throws NoApiKeyException, InputRequiredException {
        ExamUserInfo userInfo = userInfoService.selectExamUserInfoByUserId(getUserId());
        if (userInfo == null) {
            return error("请先完善个人考试信息");
        }
        ExamAnalyze temp = new ExamAnalyze();
        temp.setUserId(getUserId());
        temp.setAnalyzeYear(DateUtils.dateTimeNow(DateUtils.YYYY));
        List<ExamAnalyze> examAnalyzes = examAnalyzeService.selectExamAnalyzeList(temp);
        if (examAnalyzes == null || examAnalyzes.size() <= 0) {
            JSONObject analyze = AiUtil.getAnalyze(userInfo);
            ExamAnalyze examAnalyze = new ExamAnalyze();
            examAnalyze.setAnalyzeInfo(analyze.toString());
            examAnalyze.setUserId(getUserId());
            examAnalyze.setCreateBy(getUsername());
            examAnalyze.setCreateTime(DateUtils.getNowDate());
            examAnalyze.setAnalyzeYear(DateUtils.dateTimeNow(DateUtils.YYYY));
            examAnalyzeService.insertExamAnalyze(examAnalyze);
            return success(examAnalyze);
        }
        return success(examAnalyzes.get(0));

    }

    /**
     * 新增分析情况
     */
    @Operation(summary = "新增分析情况")
    @PreAuthorize("@ss.hasPermi('exam:analyze:add')")
    @Log(title = "分析情况", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExamAnalyze examAnalyze) {
        return toAjax(examAnalyzeService.insertExamAnalyze(examAnalyze));
    }

    /**
     * 修改分析情况
     */
    @Operation(summary = "修改分析情况")
    @PreAuthorize("@ss.hasPermi('exam:analyze:edit')")
    @Log(title = "分析情况", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExamAnalyze examAnalyze) {
        return toAjax(examAnalyzeService.updateExamAnalyze(examAnalyze));
    }

    /**
     * 删除分析情况
     */
    @Operation(summary = "删除分析情况")
    @PreAuthorize("@ss.hasPermi('exam:analyze:remove')")
    @Log(title = "分析情况", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable(name = "userIds") Long[] userIds) {
        return toAjax(examAnalyzeService.deleteExamAnalyzeByUserIds(userIds));
    }

    @PostMapping("/request/ai")
    public AjaxResult sendAi(@RequestBody JSONObject jsonObject)
            throws IOException {
        AiWebSocket.waitingSend(jsonObject.getString("sessionId"));
        Runnable task = () -> {
            try {
                String sendAi = AiUtil.sendAi(jsonObject.getString("message"));
                AiWebSocket.sendText(jsonObject.getString("sessionId"), sendAi);
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        executor.execute(task);
        return success();
    }
}
